/*
 * Util.cpp
 *
 *  Created on: 2022年6月24日
 *      Author: van
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include "macUtil.h"

using namespace std;

#ifdef HOST_RK3308
string Util::net_dev_list[1] = {
	"wlan0"
};

#else
string Util::net_dev_list[4] = {
	"wifi0",
	"eth0",
	"wlan0",
	"eno1"
};
#endif


Util::Util() {
}

int Util::get_uid(Option& option) {
	int ret;

	string uid_str = "";

	for (auto& item : net_dev_list) {
		ret = get_uid_str(item, option);
		if (ret == 0) {
			return 0;
		}
	}

	return -1;
}

int Util::get_uid_str(string& net_dev, Option& option) {
	uint8_t mac[6];

	char temp_buf[80];

	int ret = get_mac(mac, net_dev.c_str());
	if (ret == 0) {
		sprintf(temp_buf, "EDGE_%02X_%02X_%02X_%02X_%02X_%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
		option.uid = string(temp_buf);

		sprintf(temp_buf, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
		option.mac = string(temp_buf);

		sprintf(temp_buf, "%02X%02X%02X", mac[3], mac[4], mac[5]);
		option.uname = string(temp_buf);

		return 0;
	}

	return -1;
}

int Util::get_mac(uint8_t binMAC[6], const char* net_dev) {
    int sock;
    struct ifreq ifr;
    char* puc;
    memset(binMAC, 0, 6);
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == -1) {
		printf("socket error: %s\n", net_dev);
        perror("socket");
        return -1;
    }
    strcpy(ifr.ifr_name, net_dev);
    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
        close(sock);
		printf("ioctl error: %s\n", net_dev);
        perror("ioctl");
        return -1;
    }
    puc = ifr.ifr_hwaddr.sa_data;
    close(sock);
    memcpy(binMAC, puc, 6);
    return 0;
}

